<template>
  <div>
    <router-view></router-view>
    <loginModal v-show="isLogin" :isShow.sync="isLogin" @getCurrentTime="getCurrentTime"></loginModal>
    <global-uploader></global-uploader>

    <div class="colorPickBox">
      <themePicker
        :default-color="colorPick"
        @onThemeChange="themeChange"
      ></themePicker>
    </div>
    <!--<div class="colorPickBox" style="top: 230px">
      <el-color-picker v-model="backgroundColor" size="mini" @change="leftBackGroundColorChange" show-alpha></el-color-picker>
    </div>-->
  </div>
</template>
<script>
import loginModal from "@/views/login/loginModal";
import globalUploader from "@/views/fileManage/globalUploader";
import themePicker from "./template/themePicker/themePicker";

export default {
  name: "App",
 async created() {
    let _this = this;
    //   //在页面加载时读取localStorage里的状态信息
    //   let _this = this;
    //   if (window.sessionStorage.getItem(key)) {
    //     _this.$store.replaceState(
    //       Object.assign(_this.$store.state, JSON.parse(sessionStorage.getItem(key)))
    //     );
    //   }
    //   //在页面刷新时将vuex里的信息保存到localStorage里//sessionStorage
    //   window.addEventListener("beforeunload", () => {
    //     window.sessionStorage.setItem(key, JSON.stringify(_this.$store.state.user));
    //     window.sessionStorage.setItem(
    //       permission,
    //       JSON.stringify(_this.$store.state.permissionData)
    //     );
    //   });



    _this.lastTime = new Date().getTime();
     if (   productionOrEngine!=="production" && !_this.$route.name && !_this.$store.state.user ) {

       let cooike=this.getCookie()
       window.sessionStorage.setItem("x-token",cooike);
       await this.http.get(this.$api.homeLoginOthers.BPassLogin).then((res) => {
         let user = {
           userName: res.data.data.userData.userName,
           userId: res.data.data.userData.userId,
           token: res.data.data.token?res.data.data.token:cooike,
           department: res.data.data.userData.organizationName,
           nickName: res.data.data.userData.nickName,
           roleName: res.data.data.userData.roleName,
           roleInfo: res.data.data.userData.roleInfo,
           mobile: res.data.data.userData.mobile,
         };
         this.$store.dispatch("login", user); //将user保存到store中
        }).catch((item)=>{
         console.log(item);
        });
    }
  },
  data() {
    return {
      lastTime: null, // 最后一次点击的时间
      currentTime: null, // 当前点击的时间

      timeOut:2 * 60 * 60 * 1000, // 设置超时时间:2*60分钟
      isLogin: false, // 判断二次登陆是否显示
      timer: "",
      colorPick: "#5290E8",
      backgroundColor: "rgba(255, 255, 255, 0.49)",
    };
  },
  mounted() {
    let _this = this;
    this.themeChange((this.colorPick = "#5290E8"));
    this.leftBackGroundColorChange(this.backgroundColor);

    _this.$store.state.screenWidth = document.documentElement.clientWidth; //窗口宽度
    _this.$store.state.screenHeight = document.documentElement.clientHeight; //窗口高度
    //监控页面缩放
    window.onresize = () => {
      clearTimeout(_this.timer);
      _this.timer = setTimeout(() => {
        _this.$store.state.screenWidth = document.documentElement.clientWidth; //窗口宽度
        _this.$store.state.screenHeight = document.documentElement.clientHeight; //窗口高度
      }, 100);
    };

    let user = window.sessionStorage.getItem("user");
    let permission = _this.$store.state.permissionData;
    if (!user && !permission) {
      _this.$store.dispatch("setPermission");
    }
    _this.addTimeOutEventListenner();
  },
  watch: {
    $route(to, from) {
      // location.reload();
      if (to.name != "login") {
        this.render(); //调用render获取权限
      } else {
        // this.$router.replace("/pages/login");
      }
    },
  },

  methods: {
    getCookie() {
      var acookie = document.cookie.split("; ");
      var xcookie = "";
        for (var i = 0; i < acookie.length; i++) {
          var arr = acookie[i].split("=");
          if ("engine-token" == arr[0]) {
            if (arr.length > 1)
              return arr[1];
            else
              return "";
          }
        }
        return "";
    },



    getCurrentTime(dataTime) {
      this.lastTime = dataTime;
      this.isTimeOut();
    },
    //获取权限
    render() {
      this.$nextTick(function () {
        this.GlobalPermissionRender.render();
      });
    },

    //注册事件,事件触发
    addTimeOutEventListenner() {
      let _this = this;
      if (_this.$route.name !== "login") {
        document.onmousedown = (e) => {
          _this.isTimeOut();
        };
        document.onmousemove = (e) => {
          _this.isTimeOut();
        };
        document.onkeydown = (e) => {
          _this.isTimeOut();
        };
      } else {
        _this.lastTime = new Date().getTime();
      }
    },

    isTimeOut() {
      let _this = this;
      _this.beforeDealWithTimeOut();
      _this.currentTime = new Date().getTime(); // 记录这次点击的时间
      if (_this.currentTime - _this.lastTime > _this.timeOut) {
        _this.dealWithTimeOut(); //过时跳出登陆
      } else {
        _this.lastTime = new Date().getTime(); // 如果在超时范围内点击，则把这次点击的时间记录覆盖掉之前存的最后一次点击的时间
      }
    },
    //登陆过时的操作
    dealWithTimeOut() {
      let _this = this;
      let user = window.sessionStorage.getItem("user");
      if (user) {
        // 如果是登录状态
        // if (confirm("登录超时,请重新登录!")) {
        _this.lastTime = new Date().getTime();
         $(".c-app").css("filter", "blur(2px)");
        _this.isLogin = true;
        // } else {
        //   _this.$store.dispatch("removeRoute");
        //   _this.$store.dispatch("logout").then(() => {
        //     _this.$router.push({ path: "/pages/login" });
        //   });
        // }
      } else {
        //游客不设置超时
        _this.isLogin = false;
        _this.lastTime = new Date().getTime();
      }
    },
    //如果进入登陆页直接重新计时
    beforeDealWithTimeOut() {
      let _this = this;
      if (_this.$route.name === "login") {
        _this.lastTime = new Date().getTime();
        return;
      }
    },

    // 生成颜色值
    getThemeCluster(theme) {
      const tintColor = (color, tint) => {
        let red = parseInt(color.slice(0, 2), 16);
        let green = parseInt(color.slice(2, 4), 16);
        let blue = parseInt(color.slice(4, 6), 16);

        if (tint === 0) {
          // when primary color is in its rgb space
          return [red, green, blue].join(",");
        } else {
          red += Math.round(tint * (255 - red));
          green += Math.round(tint * (255 - green));
          blue += Math.round(tint * (255 - blue));

          red = red.toString(16);
          green = green.toString(16);
          blue = blue.toString(16);

          return `#${red}${green}${blue}`;
        }
      };

      const shadeColor = (color, shade) => {
        let red = parseInt(color.slice(0, 2), 16);
        let green = parseInt(color.slice(2, 4), 16);
        let blue = parseInt(color.slice(4, 6), 16);

        red = Math.round((1 - shade) * red);
        green = Math.round((1 - shade) * green);
        blue = Math.round((1 - shade) * blue);

        red = red.toString(16);
        green = green.toString(16);
        blue = blue.toString(16);

        return `#${red}${green}${blue}`;
      };
      const clusters = [theme];
      for (let i = 0; i <= 9; i++) {
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))));
      }
      clusters.push(shadeColor(theme, 0.1));
      return clusters;
    },
    // 主色調
    // 此处修改定义的变量
    themeChange(val) {
      let color = val.toString().slice(1);
      let colorData = this.getThemeCluster(color);
      this.$store.commit("changeColorThem", {
        val,
        three: colorData[3],
        seven: colorData[7],
      });
      document
        .getElementsByTagName("body")[0]
        .style.setProperty("--label-font-color", val);
      document
        .getElementsByTagName("body")[0]
        .style.setProperty("--three-color", colorData[3]);
      document
        .getElementsByTagName("body")[0]
        .style.setProperty("--hover-color", colorData[7]);
      document
        .getElementsByTagName("body")[0]
        .style.setProperty("--ten-color", colorData[10]);
    },
    // 侧边栏背景色
    leftBackGroundColorChange(val) {
      document
        .getElementsByTagName("body")[0]
        .style.setProperty("--leftBackGroundColor-color", val);
    },
  },
  components: {
    themePicker,
    loginModal,
    "global-uploader": globalUploader,
  },
};
</script>

<style lang="scss">
.colorPickBox {
  position: fixed;
  right: 4px;
  top: 4px;
  z-index: 1000000;
}
.el-color-picker__trigger{
  border: 0!important;
}

.ceshi {
  color: #f44e1b;

  color: rgb(244, 78, 27);
  color: #f56032;

  color: #f67149;

  color: #f7835f;
  color: #f89576;
  color: #faa78d;

  color: #fbb8a4;

  color: #fccabb;
  color: #fddcd1;
  color: #feede8;
  color: #dc4618;
}

// Import Main styles for this application
@import "assets/scss/style";
</style>
